package com.hgs.iias.web.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import org.springframework.beans.factory.annotation.Required;

import com.googlecode.jsonplugin.annotations.JSON;

import com.hgs.iias.domain.User;
import com.hgs.iias.service.UserService;
import com.hgs.iias.service.exception.ObjectExistsException;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private static final long serialVersionUID = 77446648856058154L;
	
	private User        user;
	private List<User>  users;
	private UserService userService;
	
	public void setEntityClass(Class<? extends User> clazz) throws IllegalAccessException, InstantiationException {
		user = clazz.newInstance();
	}
	
	@Required
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@JSON(name = "data")
	public User getModel() {
		return user;
	}
	
	public List<User> getRecords() {
		return users;
	}
	
	public boolean isSuccess() {
		return !hasErrors();
	}
	
	public String register() throws Exception {
		try {
			userService.register(getModel());
		} catch(ObjectExistsException oee) {
			addFieldError(User.ID, getText("exists", new String[] { getModel().getUsername() }));
		}
		
		return SUCCESS;
	}
	
	public String index() throws Exception {
		users = userService.list();
		
		return SUCCESS;
	}
	
	public String update() throws Exception {
		userService.modify(getModel());
		
		return SUCCESS;
	}
	
	public String view() throws Exception {
		user = userService.load(getModel().getUsername());
		
		return SUCCESS;
	}
	
	public void validateRegister() {
		if(!getModel().getPassword().equals(ServletActionContext.getRequest().getParameter(User.CONFIRM))) {
			String message = getText("inconsistent");
			
			addFieldError(User.PASSWORD, message);
			addFieldError(User.CONFIRM,  message);
		}
	}
}
